package com.springboot.killingsystem.exception;

import com.springboot.killingsystem.result.CodeMsg;
import com.springboot.killingsystem.result.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result<String> exceptionHandler(Exception e) {
        if (e instanceof BindException) {
            BindException exception = (BindException) e;
            List<ObjectError> errors = exception.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
        }else if (e instanceof GlobalException){
            GlobalException exception = (GlobalException) e;

            return Result.error(exception.getCodeMsg());
        }else {
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }
}
